﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fideeraSoft.Handlers;
using fideeraSoft.Utils;
using System.Drawing;
using System.Windows.Forms;
using fideeraSoft.Entities;
using System.Data;
using System.Data.SqlClient;

namespace fideeraSoft.Paneles
{
    class RemitoPanelBaja : PanelGeneral
    {
        private System.Windows.Forms.Button btBuscarRemitoId;
        private System.Windows.Forms.Button btBuscarRemitoCod;
        private System.Windows.Forms.TableLayoutPanel tlpBuscarRemitoId;
        private System.Windows.Forms.Button btVolver;
        private System.Windows.Forms.TextBox tbBuscarRemitoId;
        private System.Windows.Forms.TextBox tbBuscarRemitoCod;
        private System.Windows.Forms.Button btEliminar;
        private System.Windows.Forms.TableLayoutPanel tlpBuscarRemitoCod;
        private System.Windows.Forms.TableLayoutPanel tlpBotones;
        private System.Windows.Forms.DataGridView dgvRemitoBaja;

        private MetodosGenerales metGral;
        private int LocationBuscarRemitoCod = 0;
        private int locationDatagrid = 0;

        private SqlDataAdapter adapter;

        private DataSet ds;


        public RemitoPanelBaja(Handler handler)
        {
            this.formatearPanelGeneral(handler);

            metGral = new MetodosGenerales();

            this.InitializeComponent();

            this.formatearTableTitulo("BAJA DE REMITO DE ENTRADA");
            
            formatearTablaBuscarRemitoId();
            formatearTablaBuscarRemitoCod();
            
            formatearDataGrid();

            formatearTablaBotones();


            this.Controls.Add(TlpTitulo);
            this.Controls.Add(tlpBuscarRemitoId);
            this.Controls.Add(tlpBuscarRemitoCod);
            this.Controls.Add(dgvRemitoBaja);
            this.Controls.Add(tlpBotones);
        }

        #region FORMATEO

        private void formatearTablaBuscarRemitoId()
        {
            tlpBuscarRemitoId.Controls.Add(btBuscarRemitoId);
            tlpBuscarRemitoId.Controls.Add(tbBuscarRemitoId);

            tlpBuscarRemitoId.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            tlpBuscarRemitoId.BackColor = Color.LightCyan;
            tlpBuscarRemitoId.Size = new Size(400, tbBuscarRemitoId.Size.Height + 9);
            tlpBuscarRemitoId.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, this.tlpBuscarRemitoId.Size.Width), this.InitialRealPointVertical);

        }

        private void formatearTablaBuscarRemitoCod()
        {
            tlpBuscarRemitoCod.Controls.Add(btBuscarRemitoCod);
            tlpBuscarRemitoCod.Controls.Add(tbBuscarRemitoCod);


            LocationBuscarRemitoCod = this.InitialRealPointVertical + tlpBuscarRemitoId.Size.Height;
            tlpBuscarRemitoCod.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            tlpBuscarRemitoCod.BackColor = Color.LightCyan;
            tlpBuscarRemitoCod.Size = new Size(400, tbBuscarRemitoCod.Size.Height + 9);
            tlpBuscarRemitoCod.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, this.tlpBuscarRemitoCod.Size.Width), LocationBuscarRemitoCod);

        }

        private void formatearDataGrid()
        {

            locationDatagrid = LocationBuscarRemitoCod + tlpBuscarRemitoCod.Size.Height + 20 ;

            dgvRemitoBaja.AutoGenerateColumns = true;
            dgvRemitoBaja.Size = new Size(this.Size.Width - 100, 100);
            dgvRemitoBaja.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.Fill);
            dgvRemitoBaja.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllHeaders);
            dgvRemitoBaja.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvRemitoBaja.BorderStyle = BorderStyle.Fixed3D;

            dgvRemitoBaja.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, dgvRemitoBaja.Size.Width), locationDatagrid);
            
        }
        private void formatearTablaBotones()
        {
            tlpBotones.Controls.Add(btVolver);
            tlpBotones.Controls.Add(btEliminar);

            int posicionTablaBotones = locationDatagrid + dgvRemitoBaja.Size.Height + 30;
            tlpBotones.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;

            //tlpBotones.Size = new Size(400, tbBuscarProvCuil.Size.Height + 9);
            tlpBotones.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, this.tlpBotones.Size.Width), posicionTablaBotones);

        }

        #endregion

        private void InitializeComponent()
        {
            this.btBuscarRemitoId = new System.Windows.Forms.Button();
            this.btBuscarRemitoCod = new System.Windows.Forms.Button();
            this.tlpBuscarRemitoId = new System.Windows.Forms.TableLayoutPanel();
            this.btVolver = new System.Windows.Forms.Button();
            this.tbBuscarRemitoId = new System.Windows.Forms.TextBox();
            this.tbBuscarRemitoCod = new System.Windows.Forms.TextBox();
            this.btEliminar = new System.Windows.Forms.Button();
            this.tlpBuscarRemitoCod = new System.Windows.Forms.TableLayoutPanel();
            this.tlpBotones = new System.Windows.Forms.TableLayoutPanel();
            this.dgvRemitoBaja = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dgvRemitoBaja)).BeginInit();
            this.SuspendLayout();
            // 
            // btBuscarRemitoId
            // 
            this.btBuscarRemitoId.BackColor = System.Drawing.Color.AliceBlue;
            this.btBuscarRemitoId.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btBuscarRemitoId.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btBuscarRemitoId.Location = new System.Drawing.Point(0, 0);
            this.btBuscarRemitoId.Name = "btBuscarRemitoId";
            this.btBuscarRemitoId.Size = new System.Drawing.Size(75, 23);
            this.btBuscarRemitoId.TabIndex = 0;
            this.btBuscarRemitoId.Text = "Buscar Remito (ID)";
            this.btBuscarRemitoId.UseVisualStyleBackColor = false;
            this.btBuscarRemitoId.Click += new System.EventHandler(this.btBuscarRemitoId_Click);
            // 
            // btBuscarRemitoCod
            // 
            this.btBuscarRemitoCod.BackColor = System.Drawing.Color.AliceBlue;
            this.btBuscarRemitoCod.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btBuscarRemitoCod.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btBuscarRemitoCod.Location = new System.Drawing.Point(0, 0);
            this.btBuscarRemitoCod.Name = "btBuscarRemitoCod";
            this.btBuscarRemitoCod.Size = new System.Drawing.Size(75, 23);
            this.btBuscarRemitoCod.TabIndex = 0;
            this.btBuscarRemitoCod.Text = "Buscar Remito (Código)";
            this.btBuscarRemitoCod.UseVisualStyleBackColor = false;
            this.btBuscarRemitoCod.Click += new System.EventHandler(this.btBuscarRemitoCod_Click);
            // 
            // tlpBuscarRemitoId
            // 
            this.tlpBuscarRemitoId.ColumnCount = 2;
            this.tlpBuscarRemitoId.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoId.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoId.Location = new System.Drawing.Point(0, 0);
            this.tlpBuscarRemitoId.Name = "tlpBuscarRemitoId";
            this.tlpBuscarRemitoId.RowCount = 1;
            this.tlpBuscarRemitoId.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoId.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoId.Size = new System.Drawing.Size(400, 30);
            this.tlpBuscarRemitoId.TabIndex = 0;
            // 
            // btVolver
            // 
            this.btVolver.BackColor = System.Drawing.Color.AliceBlue;
            this.btVolver.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btVolver.Location = new System.Drawing.Point(0, 0);
            this.btVolver.Margin = new System.Windows.Forms.Padding(12, 3, 3, 3);
            this.btVolver.Name = "btVolver";
            this.btVolver.Size = new System.Drawing.Size(75, 40);
            this.btVolver.TabIndex = 0;
            this.btVolver.Text = "Volver";
            this.btVolver.UseVisualStyleBackColor = false;
            this.btVolver.Click += new System.EventHandler(this.btVolver_Click);
            // 
            // tbBuscarRemitoId
            // 
            this.tbBuscarRemitoId.Font = new System.Drawing.Font("Bodoni MT", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tbBuscarRemitoId.Location = new System.Drawing.Point(0, 0);
            this.tbBuscarRemitoId.MaxLength = 8;
            this.tbBuscarRemitoId.Name = "tbBuscarRemitoId";
            this.tbBuscarRemitoId.Size = new System.Drawing.Size(100, 30);
            this.tbBuscarRemitoId.TabIndex = 0;
            // 
            // tbBuscarRemitoCod
            // 
            this.tbBuscarRemitoCod.Font = new System.Drawing.Font("Bodoni MT", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tbBuscarRemitoCod.Location = new System.Drawing.Point(0, 0);
            this.tbBuscarRemitoCod.MaxLength = 10;
            this.tbBuscarRemitoCod.Name = "tbBuscarRemitoCod";
            this.tbBuscarRemitoCod.Size = new System.Drawing.Size(120, 30);
            this.tbBuscarRemitoCod.TabIndex = 0;
            // 
            // btEliminar
            // 
            this.btEliminar.BackColor = System.Drawing.Color.AliceBlue;
            this.btEliminar.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btEliminar.Location = new System.Drawing.Point(0, 0);
            this.btEliminar.Margin = new System.Windows.Forms.Padding(12, 3, 3, 3);
            this.btEliminar.Name = "btEliminar";
            this.btEliminar.Size = new System.Drawing.Size(75, 40);
            this.btEliminar.TabIndex = 0;
            this.btEliminar.Text = "Eliminar";
            this.btEliminar.UseVisualStyleBackColor = false;
            this.btEliminar.Click += new System.EventHandler(this.btEliminar_Click);
            // 
            // tlpBuscarRemitoCod
            // 
            this.tlpBuscarRemitoCod.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
            this.tlpBuscarRemitoCod.ColumnCount = 2;
            this.tlpBuscarRemitoCod.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoCod.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoCod.Location = new System.Drawing.Point(0, 0);
            this.tlpBuscarRemitoCod.Name = "tlpBuscarRemitoCod";
            this.tlpBuscarRemitoCod.RowCount = 1;
            this.tlpBuscarRemitoCod.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoCod.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarRemitoCod.Size = new System.Drawing.Size(400, 30);
            this.tlpBuscarRemitoCod.TabIndex = 0;
            // 
            // tlpBotones
            // 
            this.tlpBotones.BackColor = System.Drawing.Color.LightCyan;
            this.tlpBotones.ColumnCount = 2;
            this.tlpBotones.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.Location = new System.Drawing.Point(0, 0);
            this.tlpBotones.Name = "tlpBotones";
            this.tlpBotones.RowCount = 1;
            this.tlpBotones.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBotones.Size = new System.Drawing.Size(200, 46);
            this.tlpBotones.TabIndex = 0;
            // 
            // dgvRemitoBaja
            // 
            this.dgvRemitoBaja.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvRemitoBaja.Location = new System.Drawing.Point(0, 0);
            this.dgvRemitoBaja.Name = "dgvRemitoBaja";
            this.dgvRemitoBaja.ReadOnly = true;
            this.dgvRemitoBaja.Size = new System.Drawing.Size(240, 150);
            this.dgvRemitoBaja.TabIndex = 0;
            this.dgvRemitoBaja.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvRemitoBaja_CellContentClick);
            ((System.ComponentModel.ISupportInitialize)(this.dgvRemitoBaja)).EndInit();
            this.ResumeLayout(false);

        }

        private void dgvRemitoBaja_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            dgvRemitoBaja.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }

        private void btEliminar_Click(object sender, EventArgs e)
        {
            try
            {
                if ((dgvRemitoBaja != null) && (dgvRemitoBaja.Rows.Count != 0))
                {
                    int indx = dgvRemitoBaja.CurrentCell.RowIndex;

                    string strDataId = dgvRemitoBaja[0, indx].Value.ToString();
                    string strDataCod = dgvRemitoBaja[1, indx].Value.ToString();

                    DialogResult res = MessageBox.Show("Seguro quiere eliminar el remito: \n Código:" + strDataCod + "\n ID Remito Entrada: " + strDataId+"\nAl eliminar el remito se eliminaran los lotes asociados.", "INFO", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (res == DialogResult.Yes)
                    {

                        List<RemitoEntrada_X_Lotes> lstRemXLotes= handler.getListaRemitoEntradaXLotesPorID(strDataId);
                        if (lstRemXLotes != null)
                        {
                            foreach (RemitoEntrada_X_Lotes rmEntXLote in lstRemXLotes)
                            {

                                List<MateriaPrimaXLotes> lstMatPrimXLotes = handler.buscarListaMateriasPrimasXLotesPorID(rmEntXLote.Lote);
                                if (lstMatPrimXLotes != null)
                                {
                                    foreach (MateriaPrimaXLotes matPrimXLote in lstMatPrimXLotes)
                                    {
                                        this.handler.eliminarMateriaPrimasXLotesPorId(matPrimXLote.IdMateriaPrimaXLotes);
                                    }
                                }
                                
                                this.handler.eliminarRemitoEntradaXLotePorID(rmEntXLote.RemitoEntradaXLotes);

                                this.handler.eliminarLotePorId(rmEntXLote.Lote);

                                
                            }
                        }
                                                
                        this.handler.eliminarRemitoEntradaPorID(strDataId);

                        MessageBox.Show("Remito eliminado correctamente", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        tbBuscarRemitoCod.Clear();
                        tbBuscarRemitoId.Clear();

                        if (this.dgvRemitoBaja.DataSource != null)
                        {
                            this.dgvRemitoBaja.DataSource = null;
                        }
                        else
                        {
                            //dgvProveedorBaja.Rows.Remove(dgvProveedorBaja.Rows[e.RowIndex]);
                            //dgvProveedorBaja.Rows.Remove(dgvProveedorBaja.Rows[0]);
                            this.dgvRemitoBaja.Rows.Clear();
                        }
                        dgvRemitoBaja.Refresh();
                    }
                    else
                    {

                    }
                }
                else
                {
                    MessageBox.Show("No hay ningún remito en la lista", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (MiException exc)
            {
                MessageBox.Show("No se pudo eliminar remito. Posiblemente el remito a dar de baja posee lotes utilizados en una o más producciones.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                CLogger.Append("[btEliminar_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
            }
        }

        private void btVolver_Click(object sender, EventArgs e)
        {
            this.handler.backToPrincipal();
        }

        #region Buscar REMITOS ENTRADA SEGUN ...

        private void btBuscarRemitoCod_Click(object sender, EventArgs e)
        {
            dgvRemitoBaja.ClearSelection();
            if (this.dgvRemitoBaja.DataSource != null)
            {   
                this.dgvRemitoBaja.DataSource = null;                
            }
            else
            {
                //dgvProveedorBaja.Rows.Remove(dgvProveedorBaja.Rows[e.RowIndex]);
                //dgvProveedorBaja.Rows.Remove(dgvProveedorBaja.Rows[0]);
                
                this.dgvRemitoBaja.Rows.Clear();
            }
            dgvRemitoBaja.Refresh();

            if (!string.IsNullOrEmpty(tbBuscarRemitoCod.Text))
            {
                try
                {
                    RemitoEntrada remitoEntr = handler.buscarRemitoEntradaPorCod(tbBuscarRemitoCod.Text);
                    if (remitoEntr != null)
                    {
                        //List<RemitoEntrada> lstRemitoE = new List<RemitoEntrada>();
                        //lstRemitoE.Add(remitoEntr);

                      //  dgvRemitoBaja.DataSource = lstRemitoE;
                        //   MessageBox.Show("CARGA DE PROVEEDOR ENCONTRADO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); //DEBUG

                        string query = "SELECT re.ID AS idRemitoEntrada, re.codigo AS Código, re.fechaEntrada AS FechaDeEntrada,us.username AS Usuario,pv.razonSocial AS Proveedor,re.fechaRecepcion AS FechaDeRecepción FROM RemitoEntrada AS re INNER JOIN Usuario AS us ON us.ID=re.usuario INNER JOIN Proveedor AS pv ON pv.ID=re.proveedor WHERE re.codigo='"+tbBuscarRemitoCod.Text+"'";
                        cargarDataGridViewSegunWhere(query);
                        
                        dgvRemitoBaja.EndEdit();
                        dgvRemitoBaja.Refresh();

                    }
                    else
                    {
                        MessageBox.Show("NO SE ENCONTRO EL REMITO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        tbBuscarRemitoCod.Clear();
                    }
                }
                catch (MiException exc)
                {
                    //MessageBox.Show(exc.Message);     //DEBUG
                    CLogger.Append("[btBuscarRemitoCod_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                }
                tbBuscarRemitoCod.Clear();

            }
            else
            {
                MessageBox.Show("NO SE INGRESO NINGÚN NUMERO DE CÓDIGO", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void btBuscarRemitoId_Click(object sender, EventArgs e)
        {
            dgvRemitoBaja.ClearSelection();
            if (this.dgvRemitoBaja.DataSource != null)
            {
                this.dgvRemitoBaja.DataSource = null;
            }
            else
            {
                //dgvProveedorBaja.Rows.Remove(dgvProveedorBaja.Rows[e.RowIndex]);
                //dgvProveedorBaja.Rows.Remove(dgvProveedorBaja.Rows[0]);

                this.dgvRemitoBaja.Rows.Clear();
            }
            dgvRemitoBaja.Refresh();

            if (!string.IsNullOrEmpty(tbBuscarRemitoId.Text))
            {
                try
                {
                    RemitoEntrada remitoEntr = handler.buscarRemitoEntradaPorID(Convert.ToInt32(tbBuscarRemitoId.Text));
                    if (remitoEntr != null)
                    {

                        
                        string query = "SELECT re.ID AS idRemitoEntrada, re.codigo AS Código, re.fechaEntrada AS FechaDeEntrada,us.username AS Usuario,pv.razonSocial AS Proveedor,re.fechaRecepcion AS FechaDeRecepción FROM RemitoEntrada AS re INNER JOIN Usuario AS us ON us.ID=re.usuario INNER JOIN Proveedor AS pv ON pv.ID=re.proveedor WHERE re.ID='" + tbBuscarRemitoId.Text + "'";
                        cargarDataGridViewSegunWhere(query);

                        dgvRemitoBaja.EndEdit();
                        dgvRemitoBaja.Refresh();
                        
                    }
                    else
                    {
                        MessageBox.Show("NO SE ENCONTRO EL REMITO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        tbBuscarRemitoId.Clear();
                    }
                }
                catch (MiException exc)
                {
                    //MessageBox.Show(exc.Message);     //DEBUG
                    CLogger.Append("[btBuscarRemitoCod_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                }
                tbBuscarRemitoId.Clear();

            }
            else
            {
                MessageBox.Show("NO SE INGRESO NINGÚN NUMERO DE ID", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        #endregion


        private void cargarDataGridViewSegunWhere(string query)
        {            
            adapter = SQLclass.obtenerAdapter(query);
            if (adapter != null)
            {
                ds = new DataSet();
                adapter.Fill(ds);

                formatearDataGrid();
                dgvRemitoBaja.DataSource = ds.Tables[0];

            }
        }
              
    }
}
